import { KV } from "./addons/kv";
import { Router2 } from "./addons/router";
import configRouter from "./controllers/config";
import resourceRouter from "./controllers/resource";
import storageRouter from "./controllers/storage";
import testRouter from "./controllers/test";
import { StatusError, createCors, error } from "itty-router";

const { preflight, corsify } = createCors({
  origins: ["*"],
  methods: ["*"],
});
const router = Router2();

router.all("*", preflight);
router.all(configRouter.base, configRouter.handle);
router.all(resourceRouter.base, resourceRouter.handle);
router.all(storageRouter.base, storageRouter.handle);
router.all(testRouter.base, testRouter.handle);
router.all("*", () => {
  throw new StatusError(404, "找不到路由");
});

export default {
  async fetch(
    request: Request,
    env: { KV: KVNamespace },
    ctx: ExecutionContext
  ): Promise<Response> {
    return router
      .handle(request, { ctx, kv: new KV(env.KV) })
      .catch(error)
      .then(corsify);
  },
};
